import { platformApi } from '../../api';
import {
  PlatformLoginRequest,
  PlatformLoginResponse,
  PlatformUser,
  PlatformStats,
} from '../../../types/platform';

/**
 * 后端登录响应接口
 */
interface BackendLoginResponse {
  accessToken: string;
  user: {
    id: number;
    username: string;
    email: string;
    realName: string;
    avatar?: string;
    phone?: string;
    isSuperAdmin?: boolean;
    status: 'active' | 'inactive' | 'locked';
    createTime: string;
    updateTime: string;
    createdBy: string;
  };
  roleCodes?: string[];
  permissions?: string[];
}

/**
 * 数据转换工具函数
 */
const transformBackendLoginResponse = (backendResponse: BackendLoginResponse): PlatformLoginResponse => {
  return {
    accessToken: backendResponse.accessToken,
    token: backendResponse.accessToken, // 兼容性字段
    user: {
      id: backendResponse.user.id.toString(),
      username: backendResponse.user.username,
      email: backendResponse.user.email,
      realName: backendResponse.user.realName,
      avatar: backendResponse.user.avatar,
      phone: backendResponse.user.phone,
      isSuperAdmin: backendResponse.user.isSuperAdmin || false,
      roleIds: backendResponse.roleCodes?.join(','),
      status: backendResponse.user.status || 'active',
      createTime: backendResponse.user.createTime,
      updateTime: backendResponse.user.updateTime,
      createdBy: backendResponse.user.createdBy,
      tenantAccessType: 'all', // 默认值
    },
    permissions: backendResponse.permissions || [],
    accessibleTenants: [], // 平台管理员默认可访问所有租户
  };
};

/**
 * 平台API服务
 * 统一风格：移除try-catch，依赖响应拦截器处理错误
 * 统一风格：移除类型断言，使用明确的类型定义
 */
export const platformApiService = {
  /**
   * 平台管理员登录
   */
  login: async (loginData: PlatformLoginRequest): Promise<PlatformLoginResponse> => {
    const backendResponse = await platformApi.post('/api/v3/platform/auth/login', loginData) as BackendLoginResponse;
    return transformBackendLoginResponse(backendResponse);
  },

  /**
   * 平台管理员登出
   */
  logout: async (): Promise<void> => {
    await platformApi.post('/api/v3/platform/auth/logout');
  },

  /**
   * 刷新Token
   */
  refreshToken: async (refreshToken: string): Promise<PlatformLoginResponse> => {
    const backendResponse = await platformApi.post('/api/v3/platform/auth/refresh', {
      refreshToken,
    }) as BackendLoginResponse;
    return transformBackendLoginResponse(backendResponse);
  },

  /**
   * 获取当前用户信息
   */
  getCurrentUser: async (): Promise<PlatformUser> => {
    return platformApi.get('/api/v3/platform/auth/current-user') as Promise<PlatformUser>;
  },

  /**
   * 获取平台统计信息
   */
  getPlatformStats: async (): Promise<PlatformStats> => {
    return platformApi.get('/api/v3/platform/stats') as Promise<PlatformStats>;
  },
};

/**
 * 平台API服务导出
 * 保持与其他API服务一致的导出方式
 */
export { platformApiService as platformApi };
export default platformApiService;